package com.aiju.cash.ui.good;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.GoodsType;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.GoodTypeApi;
import com.aiju.cash.ui.good.adapter.GoodCategoryAdapter;
import com.aiju.common.ActivityStack;
import com.aiju.utils.T;
import com.aiju.widgit.dialog.EditDialog;
import com.aiju.widgit.dialog.SimpleDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2016-11-16 17:45
 * @version: V1.0
 * @Description: 商品分类
 */
public class GoodCategoryActivity extends BaseTitleActivity implements GoodCategoryAdapter.OnCategoryClick {

    private boolean isEdit;
    private ListView mListView;
    private List<GoodsType> mGoodCategories;
    private GoodTypeApi mGoodTypeApi;
    private GoodCategoryAdapter mGoodCategoryAdapter;

    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good_category);
        setCenterTitle("分类管理");

        type = getIntent().getIntExtra("type", 0);// 0 管理，1.选择
        if (type == 0) {
            mAiJuTitleBarView.setRightTitle("编辑");
            mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mAiJuTitleBarView.getRightTextView().getText().equals("编辑")) {
                        mAiJuTitleBarView.setRightTitle("完成");
                        isEdit = true;
                        if (mGoodCategoryAdapter != null) {
                            mGoodCategoryAdapter.setShowMenu(isEdit);
                            mGoodCategoryAdapter.notifyDataSetChanged();
                        }
                    } else {
                        isEdit = false;
                        mAiJuTitleBarView.setRightTitle("编辑");
                        if (mGoodCategoryAdapter != null) {
                            mGoodCategoryAdapter.setShowMenu(isEdit);
                            mGoodCategoryAdapter.notifyDataSetChanged();
                        }
                    }
                }
            });
        } else {
            setCenterTitle("选择分类");
            findViewById(R.id.btn_good_category_add).setVisibility(View.GONE);
        }
        mGoodTypeApi = new GoodTypeApi();
        getCategoryList();
        mListView = (ListView) findViewById(R.id.lv_good_category);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (type == 1) {
                    Intent intent = getIntent();
                    intent.putExtra("typeId", mGoodCategories.get(position).getId());
                    intent.putExtra("typeName", mGoodCategories.get(position).getName());
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

            }
        });
        findViewById(R.id.btn_good_category_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddDialog();
            }
        });
    }

    /**
     * 显示添加商品对话框
     */
    private void showAddDialog() {
        new EditDialog(GoodCategoryActivity.this)
                .setLayoutParams()
                .setOnEditClick(new EditDialog.OnEditClick() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onSubmit(String msg) {
                        if (TextUtils.isEmpty(msg)) {
                            T.ToastShort("请输入分类名称");
                            return;
                        }
                        saveGoodType(msg);
                    }
                }).show();
    }

    /**
     * 获取商品分列表
     */
    private void getCategoryList() {
        mDialogHelper.showLoadingProgressDialog();
        mGoodTypeApi.goodTypeList(mUser.getShop().getStoreId(), mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    mGoodCategories = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<ArrayList<GoodsType>>() {
                    }.getType());
                    if (mGoodCategories.size() != 0) {
                        mGoodCategoryAdapter = new GoodCategoryAdapter(GoodCategoryActivity.this, mGoodCategories);
                        mGoodCategoryAdapter.setOnCategoryClick(GoodCategoryActivity.this);
                        mGoodCategoryAdapter.setShowMenu(isEdit);
                        mListView.setAdapter(mGoodCategoryAdapter);
                    }
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    @Override
    public void onDelete(final GoodsType goodsType) {
        new SimpleDialog(GoodCategoryActivity.this)
                .setLayoutParams()
                .setOnSimpleClick(new SimpleDialog.OnSimpleClick() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onSubmit() {
                        deleteGoodType(goodsType);
                    }
                }).show();
    }

    @Override
    public void onEdit(final GoodsType goodsType) {
        new EditDialog(GoodCategoryActivity.this)
                .setLayoutParams()
                .setTitileText("修改分类名称")
                .setContentText(goodsType.getName())
                .setOnEditClick(new EditDialog.OnEditClick() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onSubmit(String msg) {
                        editGoodType(msg, goodsType);
                    }
                }).show();

    }

    /**
     * 新增分类
     *
     * @param mame
     */
    private void saveGoodType(String mame) {
        mGoodTypeApi.goodSave(mame, mUser.getShop().getStoreId(), mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    load = true;
                    T.ToastShort("创建成功");
                    getCategoryList();
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }


    /**
     * 删除分类
     *
     * @param goodsType
     */
    private void deleteGoodType(final GoodsType goodsType) {
        mGoodTypeApi.goodDelete(goodsType.getId(), mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    load = true;
                    T.ToastShort("删除成功");
                    mGoodCategories.remove(goodsType);
                    mGoodCategoryAdapter.notifyDataSetChanged();
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    /**
     * 更新商品分类
     *
     * @param name
     * @param goodsType
     */
    private void editGoodType(final String name, final GoodsType goodsType) {
        mGoodTypeApi.goodUpdate(name, goodsType.getId(), mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    T.ToastShort("修改成功");
                    load = true;
                    goodsType.setName(name);
                    mGoodCategoryAdapter.notifyDataSetChanged();
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    private boolean load = false;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (load) {
            ActivityStack.finish(ActivityStack.findActivity(GoodActivity.class.getName()));
            startActivity(GoodActivity.class);
        }
    }
}
